package com.lotus.tep.util;

import com.lotus.tep.constant.EPaperConstants;
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;

public class SpeechUtil {

	private static String voiceName_;

	static {
		setKevin16Voice();
	}

	public static synchronized void speakIt(String toSpeak) {
		toSpeak = clearHtmlFormatting(toSpeak);
		Voice voice = VoiceManager.getInstance().getVoice(voiceName_);
		voice.allocate();
		voice.speak(toSpeak);
		voice.deallocate();
		System.gc();/* memory clean-up required!! */
	}

	public static synchronized void setKevinVoice() {
		voiceName_ = EPaperConstants.VOICE_NAME_KEVIN;
	}

	public static synchronized void setKevin16Voice() {
		voiceName_ = EPaperConstants.VOICE_NAME_KEVIN_16;
	}

	private static synchronized String clearHtmlFormatting(String html) {
		String text = html;
		if (null != text) {
			text = text.trim();
			text = text.replaceAll(EPaperConstants.HTML_NEW_LINE_1, EPaperConstants.BLANK_TEXT);
			text = text.replaceAll(EPaperConstants.HTML_NEW_LINE_2, EPaperConstants.BLANK_TEXT);
			text = text.replaceAll(EPaperConstants.HTML_NEW_LINE_1.toUpperCase(), EPaperConstants.BLANK_TEXT);
			text = text.replaceAll(EPaperConstants.HTML_NEW_LINE_2.toUpperCase(), EPaperConstants.BLANK_TEXT);
			text = text.replaceAll(EPaperConstants.HTML_SPACE, EPaperConstants.PLAIN_TEXT_SPACE);
			text = text.replaceAll(EPaperConstants.HTML_COMMENT, EPaperConstants.BLANK_TEXT);

		}
		System.out.printf("toSpeak text: %s\n", text);
		return text;
	}
}
